<template>
  <div>
    <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employee" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { getNewDepartment, getDepById, updateDepartmentInfo } from '@/api/department'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validateCode = (rule, value, callback) => {
      let codeList = this.originList.map(item => item.code)
      // console.log(codeList)

      // 编辑部门
      if (this.isEdit) {
        // 当处于编辑部门时 , 部门编码如果没有修改 , 不需要提示
        codeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }

      if (codeList.includes(value)) {
        callback(new Error(value + '部门编码已存在'))
      } else {
        callback()
      }
    }

    const validateName = (rule, value, callback) => {
      // console.log(this.originList)
      // console.log(this.pid)

      // 找到当前部门的pid
      const pid = this.originList.find(item => item.id === this.id).pid
      console.log(this.originList.find(item => item.id === this.id))
      // console.log(this.originList.find(item => item.id === this.id))
      let nameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // console.log(nameList)

      if (this.isEdit) {
        // 有父级pid之后 , 筛选出该pid下的所有子部门的部门名称 , 并排除当前部门
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.id).map(item => item.name)
        // console.log(nameList)
      }

      if (nameList.includes(value)) {
        callback(new Error(value + '已经存在'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      formRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['change', 'blur'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      employee: [],
      success: true // 添加修改是否完成
    }
  },
  created() {
    // 获取员工姓名
    this.loadEmployee()
    // 点击确定 完成添加
    // this.hSubmit()
    // 根据id获取部门信息
    this.loadDepartment()
  },
  methods: {
    hSubmit() {
      // 表单校验
      this.$refs.form.validate(valid => {
        // console.log(valid)
        if (!valid) return
        if (!this.isEdit) {
          this.doAdd()
        } else {
          this.doEdit()
        }
      })
    },
    hCancel() {
      this.$emit('closeDialog', !this.success)
      // this.$refs.form.resetFields() // 用 v-if 不需要手动清空表单
    },
    async loadEmployee() {
      const res = await getEmployeeSimple()
      //   console.log(res)
      this.employee = res.data
    },
    // 数据回填 -> 编辑
    async  loadDepartment() {
      // 判断是否处于编辑状态
      if (!this.isEdit) return
      try {
        const res = await getDepById(this.id)
        //   console.log(res)
        this.form = res.data
      } catch (e) {
        console.log('获取部门详情失败,原因是:', e)
      }
    },
    // 点击确定 , 完成新增
    async doAdd() {
      try {
        // console.log({ ...this.form, pid: this.pid })
        const res = await getNewDepartment({ ...this.form, pid: this.id })
        // console.log(res)
        this.$message.success(res.message)
        this.$emit('closeDialog', this.success)
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 点击确定 , 完成修改
    async  doEdit() {
      try {
        const res = await updateDepartmentInfo(this.form)
        // console.log(this.form.id)
        this.$message.success(res.message)
        this.$emit('closeDialog', this.success)
      } catch (e) {
        this.$message.error(e.message)
      }
    }
  }
}
</script>

